package app

import (
	"encoding/json"
	"os/exec"
	"strconv"

	"gitee.com/extrame/fb-runner/util"
	"github.com/sirupsen/logrus"
)

func Approve(base string, codes ...*Chaincode) error {
	var codeMap = make(map[string]*Chaincode)
	var force = false
	if codes == nil {
		codeMap = GetInstalledChaincodes()
	} else {
		for _, code := range codes {
			codeMap[code.PackageId] = code
			force = true
		}
	}
	for pid, c := range codeMap {
		logrus.Infoln("待批准以下代码：", pid)
		if (c.Approved && !force) || c.Historic {
			logrus.WithField("Force", force).WithField("Approved", c.Approved).WithField("是历史版本", c.Historic).Infoln("跳过该版本")
			continue
		}
		newLabel := c.GenerateVersionLabel()
		if !util.AskForConfirmation("使用建议版本标签：" + newLabel + "吗？") {
			newLabel = util.GetAnswer("请输入版本标签：")
		}
		c.VersionLabel = newLabel
		c.Version++
		if c.Channel == "" {
			c.Channel = util.GetAnswer("请输入该应用部署的Channel名称：")
		}
		if c.Name == "" {
			c.Name = util.GetAnswer("请输入该应用的部署名称：")
		}
		for _, org := range util.Config.GetPeerOrganizations() {
			//peer lifecycle chaincode       anhuiceshi  anhuidata --version 1.1.3   --sequence 14 --tls true
			args := []string{"lifecycle", "chaincode", "approveformyorg",
				"--channelID", c.Channel, "--name", c.Name, "--version", c.VersionLabel, "--init-required",
				"--package-id", pid, "--sequence", strconv.FormatUint(c.Version, 10)}
			args = append(args, util.Config.GetOrdererOrganization().GetConnArgs(base)...)
			cmd := exec.Command("peer", args...)

			util.UseOrg(cmd, base, org, true)
			if force {
				logrus.Infoln("Approve by ", cmd.String())
			}
			_, _, err := util.Run(cmd)
			if err != nil {
				return err
			}
			logrus.Info("完成授权：", c)
			c.Approved = true
			UpdateChaincode(c)
		}
	}
	return nil
}

//TODO 应该把名称改一下，现在除了approved还可以check committed
func CheckApprove(base, action, channel, name string) error {
	if channel == "" {
		channel = util.GetAnswer("请输入该应用部署的Channel名称：")
	}
	if name == "" {
		name = util.GetAnswer("请输入该应用的部署名称：")
	}
	//peer lifecycle chaincode install ~/anhui1.tar.gz
	for _, org := range util.Config.GetPeerOrganizations() {
		cmd := exec.Command("peer", "lifecycle", "chaincode", "query"+action, "--name", name, "--output", "json", "-C", channel)
		util.UseOrg(cmd, base, org, true)
		stdout, _, err := util.Run(cmd)
		if err != nil {
			return err
		}
		var out OutputJson
		json.Unmarshal([]byte(stdout), &out)
		logrus.Info(string(stdout))
		newCode := CheckNewInstall(out.InstalledChaincodes)
		logrus.Info("完成安装确认：", newCode)
		AddChaincode(newCode...)
	}
	return nil
}
